package com.cj.controller;

import java.util.List;

import com.cj.model.Department;
import com.cj.model.Employee;
import com.cj.model.Post;
import com.cj.model.PostSalary;
import com.cj.utils.StrUtil;
import com.jfinal.core.Controller;

public class PostController extends Controller {
	
	public void index() {
		List<Post> post = Post.me.getAllPosts();
		List<Department> departments = Department.me.getAllDepartments();
		setAttr("posts", post);
		setAttr("departments", departments);
		render("postInfo.jsp");
	}
	
	public void edit() {
		getModel(Post.class).update();
		redirect("/post");
	}
	
	public void add() {
		Post post = getModel(Post.class);
		Integer maxId = Post.me.getMaxID();
		if(maxId == null) {
			maxId = -1;
		}
		String postNo = StrUtil.getNo("P", "000", maxId + 1);
		post.remove("postId");
		post.set("postNo", postNo).save();
		redirect("/post");
	}
	
	public void delete() {
		Integer postId = getParaToInt("postId");
		List<Employee> employees = Employee.me.getEmployeesByPost(postId);
		PostSalary postSalary = PostSalary.me.getPostSalaryByPost(postId);
		if((employees == null || employees.isEmpty()) && postSalary == null) {
			Post.me.deleteById(getParaToInt("postId"));
			renderJson("flag", true);
		} else {
			renderJson("flag", false);
		}
		
		
	}
	
	public void postsByDept() {
		int deptId =  getParaToInt("deptId");
		List<Post> posts = Post.me.getPostsByDept(deptId);
		renderJson("posts", posts);
	}
}
